<?php

namespace Home\Controller;

use Utuo\ForegroundController;

class ArticleController extends ForegroundController {
	
	private $tagName = 'article';
	
	// 详细页
	public function showAction() {
		$id = I('id', 0, 'intval'); // 文章id
		$data = M()->table("__MODEL_ARTICLE__ this0")
							->join("__MODEL_ARTICLE_CONFIG__ this1 on this0.id = this1.id", 'LEFT')
							->where("id=%d", $id)
							->find();
		if($data){
			$data['tags'] = $this->getTagNames($data['tags'], $this->sid);
		}
		$this->assign("content", $data);
		$this->display($this->getTemplete($this->tagName, 'content'));
	}
	
	// 更多
	public function moreAction() {
		$list = $this->lists($this->catId, true, $this->getPageSize(), $this->getPage());
		$totalPages = ceil($list['count'] / $this->getPageSize()); //总页数
		// 显示更多文章数据
		$data = array();
		if($this->getPage() <= $totalPages) {
			$data = $list['data'];
			foreach ($data as &$v) $v['url'] = get_content_url($this->tagName, $this->sid, $this->catId, $v['id']);
		}
		$this->ajaxSuccess('', $data);
	}
	
	// 文章列表
	public function listAction() {
		$this->display();
	}
	
	private function lists($cateId = 0, $paginate = false, $pageSize = 10, $p = 1) {
		$condition = array(
				"this0.cid" => $this->sid,
				"this0.is_deleted" => 0,
				"this0.cat_id" => $cateId
		);
		$m = M()->table("__ARTICLE__ this0")->join("__ARTICLE_CONFIG__ this1 on this0.id = this1.id", 'LEFT')->where($condition);
		$new_m = clone $m;
		// 分页处理
		if($paginate) {
			$m->limit($this->getPageSize())->page($this->getPage());
			$contentCount = $new_m->count();
		}
		$contentLists = $m->order('this0.update_time desc')->select();
		return array('count' => $contentCount, 'data' => $contentLists);
	}
	
	// 获得标签名
	private function getTagNames($ids, $aid) {
		if ($ids) {
			$names = M ( "Tags" )->where ( array (
					"id" => array (
							"in",
							$ids
					),
			) )->getField ( "name", true );
					return join ( ',', $names );
		}
		return "";
	}
	
}